package com.wen.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.wxpay.sdk.WXPayUtil;
import com.wen.order.api.EduApi;
import com.wen.order.entity.TOrder;
import com.wen.order.entity.TPayLog;
import com.wen.order.mapper.TPayLogMapper;
import com.wen.order.service.TOrderService;
import com.wen.order.service.TPayLogService;
import com.wen.order.util.HttpClient;
import com.wen.servicebase.exception.BusinessException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 支付日志表 服务实现类
 * </p>
 *
 * @author wen
 * @since 2021-06-19
 */
@Service
public class TPayLogServiceImpl extends ServiceImpl<TPayLogMapper, TPayLog> implements TPayLogService {
    @Resource
    private TOrderService orderService;
    @Resource
    private EduApi eduApi;

    /**
     * 根据订单号生成对应的微信支付二维码
     *
     * @param orderNo 订单号
     * @return 返回二维码地址和其他信息
     */
    @Override
    public Map<String, Object> createNative(String orderNo) {
        try {
//            1.根据订单号查询订单信息
            QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
            wrapper.eq("order_no", orderNo);
            TOrder order = orderService.getOne(wrapper);

            Map<String, String> m = new HashMap<>();
//            2.使用map设置生成二维码需要的参数
            m.put("appid", "wx74862e0dfcf69954");//微信id
            m.put("mch_id", "1558950191");//商户号
            m.put("nonce_str", WXPayUtil.generateNonceStr());//生成随机的字符串
            m.put("body", order.getCourseTitle());
            m.put("out_trade_no", orderNo);
            m.put("total_fee", order.getTotalFee().multiply(new BigDecimal("1")).longValue() + "");
            m.put("spbill_create_ip", "127.0.0.1");//项目地址
            m.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify\n");
            m.put("trade_type", "NATIVE");

//            3.发送httpclient请求,传递xml格式参数,请求地址为微信支付提供的固定地址
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");

            //client设置参数
            client.setXmlParam(WXPayUtil.generateSignedXml(m, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));//商户key
            client.setHttps(true);//默认不支持https的访问,设置为true,即可以支持https访问
            client.post();//执行请求发送(post\get等方式)
            //返回第三方的数据(xml格式的返回数据)
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
//            4.得到发送请求返回的结果
            Map<String, Object> map = new HashMap<>();
            map.put("out_trade_no", orderNo);
            map.put("course_id", order.getCourseId());
            map.put("total_fee", order.getTotalFee());
            map.put("result_code", resultMap.get("result_code"));//返回二维码操作的状态码
            map.put("code_url", resultMap.get("code_url"));//返回二维码的地址
            //微信支付二维码2小时过期，可采取2小时未支付取消订单
            //redisTemplate.opsForValue().set(orderNo, map, 120, TimeUnit.MINUTES);
            return map;
        } catch (Exception e) {
            throw new BusinessException("二维码生成失败");
        }


    }

    /**
     * 根据订单号向微信支付平台查询订单支付状态
     *
     * @param orderNo 订单号
     * @return result of operation
     */
    @Override
    public Map<String, String> queryPayStatus(String orderNo) {
        try {
            //1、封装参数
            Map<String, String> m = new HashMap<>();
            m.put("appid", "wx74862e0dfcf69954");
            m.put("mch_id", "1558950191");
            m.put("out_trade_no", orderNo);
            m.put("nonce_str", WXPayUtil.generateNonceStr());

            //2、设置请求
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(m, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);
            client.post();
            //3、返回第三方的数据
            String xml = client.getContent();
            //4、转成Map
            //5、返回
            return WXPayUtil.xmlToMap(xml);
        } catch (Exception e) {
            throw new BusinessException("订单支付异常");
        }
    }

    /**
     * 添加记录到支付日志表,并修改订单表的状态
     *
     * @param map 要修改的信息
     */
    @Override
    public void updateOrderStatus(Map<String, String> map) {
//        获取订单号
        String orderNo = map.get("out_trade_no");
//        根据订单号查询订单信息
        QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no", orderNo);
        TOrder order = orderService.getOne(wrapper);
//        查看订单信息状态
        if (order.getStatus() == 1) return;
        order.setStatus(1);
//            更新订单状态信息
        orderService.updateById(order);
//        更新课程购买数
        String courseId = order.getCourseId();
        eduApi.updateCourseInfo(courseId);

//      添加记录到支付日志表中
        TPayLog payLog = new TPayLog();
        payLog.setOrderNo(order.getOrderNo());//支付订单号
        payLog.setPayTime(new Date(System.currentTimeMillis()));//订单完成支付时间
        payLog.setPayType(1);//支付类型-微信支付
        payLog.setTotalFee(order.getTotalFee());//总金额(分)
        payLog.setTradeState(map.get("trade_state"));//支付状态
        payLog.setTransactionId(map.get("transaction_id"));//订单流水号
        payLog.setAttr(JSONObject.toJSONString(map));//其他的订单信息
        baseMapper.insert(payLog);//插入到支付日志表
    }
}

